"""
@name : collects
@author : FanMY_71
@projectname: Selling-Idea
@Time: 2022/9/5-20:44
"""
from flask import Blueprint, request
from flask_restful import Api, Resource

from libs.handler import default_error_handler
from libs.response import generate_response
from model import db
from model.collect import Collect

collect_bp = Blueprint("collect", __name__, url_prefix="/v1")
api = Api(collect_bp)


class CollectView(Resource):
    def put(self):
        """
        收藏
        获取文章id、用户id
        :return:收藏成功、文章id
        """
        user_id = request.json.get("userid")
        article_id = request.json.get("articleid")
        # 查找用户的收藏信息
        collect_infos = Collect.query.filter_by(user_id=user_id).all()
        for collect_info in collect_infos:
            # 如果该用户曾经收藏过该文章
            if collect_info.article_id == article_id and collect_info.collect == "Y":
                # 取消收藏
                collect_info.collect = "N"
                db.session.add(collect_info)
                db.session.commit()
                return generate_response(message="已取消收藏", data=article_id)
        # 用户没有收藏过该文章
        new_collect = Collect(user_id=user_id, article_id=article_id, collect="Y")
        db.session.add(new_collect)
        db.session.commit()
        return generate_response(message="收藏成功", data=article_id)


api.add_resource(CollectView, "/collects")
api.handle_error = default_error_handler
